//
//  ClusterListPacketCenter.m
//  HiQ
//
//  Created by arvintan on 12-8-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ClusterListPacketCenter.h"
#import "MainWindowController.h"
#import "MacrosDefine.h"
#import "ClusterObjects.h"
#import "Buddy.h"

@implementation ClusterListPacketCenter

- (void)onGetClusterList
{
    Buddy *myInfo = [MainWindowController shareMyselfInfo];
    NSInteger qqNum = myInfo->buddyQQ;
    
    NSData *sendData = [[NSData alloc] initWithBytes:&(qqNum) length:sizeof(NSUInteger)];
    [[Connection sharedServerConnection] sendData:sendData cmd:CMD_FUN_GROUP subcmd:CMD_GROUP_LIST_REQUEST];
}


- (void)onReceiveClusterListPacket:(NSData *)data
{
    void *bytes = (void*)([data bytes]+16);
    
    CLUSTERLISTREPLYHRD *replyHrd = (CLUSTERLISTREPLYHRD*)bytes;
    if (replyHrd->error != GROUP_CREATE_NO_ERROR) 
    {
        //NSLog(@"ClusterListReply Error:");
        return;
    }
    
    NSUInteger count = replyHrd->count;
    NSUInteger groupIDLen = replyHrd->groupIDLen;
    NSUInteger groupNameLen = replyHrd->groupNameLen;
    NSUInteger groupImageLen = replyHrd->groupImageLen;
    
    NSData *groupIDData = [[NSData alloc] initWithBytes:(bytes + 5*sizeof(NSUInteger)) length:groupIDLen];
    NSArray *groupIDArray = [NSKeyedUnarchiver unarchiveObjectWithData:groupIDData];
    
    NSData *groupNameData = [[NSData alloc] initWithBytes:(bytes + 5*sizeof(NSUInteger)+groupIDLen) length:groupNameLen];
    NSArray *groupNameArray = [NSKeyedUnarchiver unarchiveObjectWithData:groupNameData];
    
    NSData *groupImageData = [[NSData alloc] initWithBytes:(bytes + 5*sizeof(NSUInteger) +groupIDLen + groupNameLen) length:groupImageLen];
    NSArray *groupImageArray = [NSKeyedUnarchiver unarchiveObjectWithData:groupImageData];
    
    NSMutableArray *clusterGroupArray = [[[MainWindowController sharedMainWindowController] clusterSource] clusterGroupArray];
    ClusterGroup *discussion = [clusterGroupArray objectAtIndex:0];
    for (NSUInteger i = 0 ; i < count ; ++i ) {
        Cluster *cluster = [[Cluster alloc] init];
        cluster->clusterId = [[groupIDArray objectAtIndex:i] integerValue];
        cluster->clusterName = [groupNameArray objectAtIndex:i];
        cluster->photo = [groupImageArray objectAtIndex:i];
        [discussion->clusterList addObject:cluster];
    }
    
    [[[MainWindowController sharedMainWindowController] clusterOutlineView] reloadData];
}

@end
